package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.sql.visitor.functions.Concat;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.db.entity.AgentAppEntity;
import com.fjwt.gz.db.entity.AgentScoreEntity;
import com.fjwt.gz.db.entity.AgentScoreRuleEntity;
import com.fjwt.gz.db.entity.SysConfig;
import com.fjwt.gz.db.vo.AgentScoreRuleVO;
import com.fjwt.gz.db.vo.ScoreRuleAndTotalVO;
import com.fjwt.gz.service.mapper.AgentScoreRuleMapper;
import com.fjwt.gz.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 机构会员积分规则表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AgentScoreRuleService extends ServiceImpl<AgentScoreRuleMapper, AgentScoreRuleEntity> {

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private AgentScoreService agentScoreService;
    @Autowired
    private AgentAppService agentAppService;

    public List<AgentScoreRuleEntity> scoreRuleList(String appId) {
        return baseMapper.findScoreRuleListByAppId(appId);
    }

    /**
     * 获取积分规则列表
     *
     * @param iPage
     * @param agentScoreRuleVO
     * @return
     */
    public IPage<ScoreRuleAndTotalVO> findScoreRuleLists(IPage iPage, AgentScoreRuleVO agentScoreRuleVO) {
        if (Constants.SYS_ROLE_TYPE.PROXY.equals(agentScoreRuleVO.getSysType()) && !checkIsProxy(agentScoreRuleVO)) {
            return new Page<>();
        }
        return baseMapper.findScoreRuleLists(iPage, agentScoreRuleVO);
    }

    /**
     * 是否属于机构端
     *
     * @param agentScoreRuleVO
     * @return
     */
    private Boolean checkIsProxy(AgentScoreRuleVO agentScoreRuleVO) {
        AgentScoreEntity agentScore = agentScoreService.getAgentScoreByAgentNo(agentScoreRuleVO.getCurrentCreatedAgentNo());
        List<AgentAppEntity> agentAppList = agentAppService.list(
                AgentAppEntity.gw()
                        .eq(AgentAppEntity::getAgentNo, agentScoreRuleVO.getCurrentCreatedAgentNo())
                        .eq(AgentAppEntity::getType, Constants.AGENT_APP_TYPE.WX_LITE)
                        .eq(AgentAppEntity::getIsDeleted, Constants.IS_DELETED.NO)
                        .eq(AgentAppEntity::getIsDefault, 1)
        );
        if (ObjectUtil.isEmpty(agentScore) || ObjectUtil.isEmpty(agentAppList)) {
            return false;
        }
        return true;
    }

    /**
     * 获取规则详情
     *
     * @param scoreRuleId
     * @return
     */
    public ScoreRuleAndTotalVO queryRuleAndTotalByRuleId(String scoreRuleId) {
        if (StringUtils.isEmpty(scoreRuleId)) {
            throw new RuntimeException("请求参数缺失！");
        }
        return baseMapper.queryRuleAndTotalByRuleId(scoreRuleId);
    }

    /**
     * 获取积分规则
     *
     * @param agentNo
     * @return
     */
    public IPage<AgentScoreRuleVO> findScoreRuleList(IPage iPage, String agentNo) {
        if (StringUtils.isEmpty(agentNo)) {
            throw new RuntimeException("机构编号不能为空");
        }
        IPage<AgentScoreRuleEntity> scoreRuleList = baseMapper.findScoreRuleList(iPage, agentNo);
        //转换
        List<AgentScoreRuleVO> voList = scoreRuleList.getRecords().stream().map(
                entity -> {
                    AgentScoreRuleVO vo = BeanUtil.copyProperties(entity, AgentScoreRuleVO.class);
                    return vo;
                }).toList();
        IPage<AgentScoreRuleVO> page = new Page<>();
        page.setRecords(voList);
        page.setTotal(scoreRuleList.getTotal());
        page.setCurrent(scoreRuleList.getCurrent());
        page.setSize(scoreRuleList.getSize());
        return page;
    }

    public List<SysConfig> getSysConfig() {
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysConfig::getGroupKey, Constants.POINT.POINT_PRODUCE);
        List<SysConfig> list = sysConfigService.getBaseMapper().selectList(queryWrapper);
        return new ArrayList<>(list);
    }

    /**
     * 积分规则新增
     *
     * @param entity
     * @return
     */
    public int scoreRuleSave(AgentScoreRuleEntity entity) {
        String agentNo = entity.getExt().getString("agentNo");
        if (StringUtils.isEmpty(agentNo)) {
            throw new BizException("请求参数缺失！");
        }
        List<AgentAppEntity> agentAppEntityList = agentAppService.list(
                AgentAppEntity.gw()
                        .eq(AgentAppEntity::getAgentNo, agentNo)
                        .eq(AgentAppEntity::getType, Constants.AGENT_APP_TYPE.WX_LITE)
                        .eq(AgentAppEntity::getIsDefault, 1)
                        .eq(AgentAppEntity::getIsDeleted, Constants.IS_DELETED.NO)
        );
        if (ObjectUtil.isEmpty(agentAppEntityList)) {
            throw new BizException("当前机构不存在默认的应用");
        }
        if (agentAppEntityList.size() > 1) {
            throw new BizException("该机构当前默认应用不唯一");
        }
        if (null != entity.getOverType() && 2 == entity.getOverType()) {
            entity.setOverTime(Utils.firstMonthLastDay());
        }

        List<AgentScoreEntity> list = agentScoreService.list(
                AgentScoreEntity.gw()
                        .eq(AgentScoreEntity::getAgentNo, agentNo)
                        .eq(AgentScoreEntity::getIsDefault, 0));
        if (ObjectUtil.isEmpty(list) || list.size() > 1) {
            throw new BizException("机构积分类别数据异常");
        }
        entity.setAgentScoreId(list.get(0).getAgentScoreId());
        entity.setCreatedAt(new Date());
        return baseMapper.insert(entity);
    }

    /**
     * 修改积分规则
     *
     * @param entity
     * @return
     */
    public int updateScoreRule(ScoreRuleAndTotalVO entity) {
        // 积分细则
        AgentScoreRuleEntity ruleEntity = new AgentScoreRuleEntity();
        ruleEntity.setRuleKey(entity.getRuleKey());
        ruleEntity.setRuleJson(entity.getRuleJson());
        ruleEntity.setState(entity.getState());
        if (null != entity.getOverType() && 2 == entity.getOverType()) {
            ruleEntity.setOverTime(Utils.firstMonthLastDay());
        } else {
            ruleEntity.setOverTime(entity.getOverTime());
        }
        ruleEntity.setOverDays(entity.getOverDays());
        ruleEntity.setOverType(entity.getOverType());
        ruleEntity.setRemark(entity.getRemark());
        ruleEntity.setScoreRuleName(entity.getScoreRuleName());
        ruleEntity.setScoreRuleId(entity.getScoreRuleId());
        ruleEntity.setUpdatedAt(new Date());
        ruleEntity.setScoreRuleDes(entity.getScoreRuleDes());
        // 总积分规则
        return baseMapper.updateById(ruleEntity);
    }

    /**
     * 删除积分规则
     *
     * @param scoreRuleId
     * @return
     */
    public int deleteById(Long scoreRuleId) {
        if (Objects.isNull(scoreRuleId)) {
            throw new RuntimeException("请求参数缺失！");
        }
        return baseMapper.deleteById(scoreRuleId);
    }

    /**
     * 积分规则管理状态变更（启用/不启用）
     *
     * @param entity
     * @return
     */
    public Boolean updateStateById(AgentScoreRuleEntity entity) {
        if (Objects.isNull(entity.getScoreRuleId()) || Objects.isNull(entity.getState())) {
            throw new RuntimeException("请求参数缺失！");
        }
        return this.lambdaUpdate()
                .set(AgentScoreRuleEntity::getState, entity.getState())
                .eq(AgentScoreRuleEntity::getScoreRuleId, entity.getScoreRuleId())
                .update();
    }
}
